package com.qiche.controller.mini;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qiche.aspect.Result;
import com.qiche.enums.ResultEnum;
import com.qiche.model.StoreMember;
import com.qiche.service.StoreMemberService;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信小程序端 登录控制器
 * @author chendezhi
 * @date 2018/3/2 16:01
 */
@Slf4j
@RestController
@RequestMapping("/wap")
public class WxLoginController {

    @Autowired
    private StoreMemberService storeMemberService;

    @Autowired
    private HttpSession session;


    /**
     * 微信登录
     * @param unionid
     * @return
     */
    @PostMapping("/member/login")
    public Result memberLogin(String openid, String unionid, Long merchantid) {
        if (StringUtils.isEmpty(unionid)) {
            //参数错误
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }

        
      //  Member member = memberService.selectByUnionid(unionid);
        StoreMember storeMember=storeMemberService.selectByOpenidMerchantid(openid,merchantid);
        if (storeMember == null) {
            //说明查询不出用户 没有用户注册过
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }

        session.setAttribute("member", storeMember);
        return Result.createByResultEnum(ResultEnum.SUCCESS);
    }
    

    /**
     * 小程序微信登录(获取用户unionid)
     * @param encryptedData
     * @param iv
     * @param code
     * @return
     *//*
    @PostMapping("/member/decodeUserInfo")
    public Result decodeUserInfo(@RequestParam("encryptedData") String encryptedData,
                                 @RequestParam("iv") String iv,
                                 @RequestParam("code") String code) {

        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }

//        //小程序唯一标识   (在微信小程序管理后台获取)
//        String wxspAppid = "xxxxxxxxxxxxxx";
//        //小程序的 app secret (在微信小程序管理后台获取)
//        String wxspSecret = "xxxxxxxxxxxxxx";
        //授权（必填）
        String grant_type = "authorization_code";

//////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + wxAppid + "&secret=" + wxSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        log.info("decodeUserInfo,获取用户openid::::{}",json.toJSONString());
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        //////////////// 2、对encryptedData加密数据进行AES解密 ////////////////
        try {
            String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                JSONObject userInfoJSON = JSONObject.parseObject(result);
                log.info("decodeUserInfo,获取用户所有信息::::{}",userInfoJSON.toJSONString());
                String unionId = userInfoJSON.getString("unionId");
                if (StringUtils.isEmpty(unionId)){
                    return Result.createByResultEnum(ResultEnum.GET_WX_UNIONID_ERROR);
                }
                Member member = memberService.selectByUnionid(unionId);
                if (member == null || StringUtils.isEmpty(member.getMemberPhone())) {
                    //说明没有注册过.
                    String nickName = userInfoJSON.getString("nickName");
                    String avatarUrl = userInfoJSON.getString("avatarUrl");
                    Member sessionMember = new Member();

                    sessionMember.setMemberNickname(EmojiParser.removeAllEmojis(nickName));
                    sessionMember.setHeadimgurl(avatarUrl);
                    sessionMember.setUnionid(unionId);
//                    存入session中
                    session.setAttribute("member", sessionMember);
                    return Result.createByResultEnum(ResultEnum.RETRUN_REGISTER_PAGE);
                } else {
                    //说明数据库有数据直接 存入session登陆
                    session.setAttribute("member", member);
                    return Result.createByResultEnum(ResultEnum.SUCCESS);
                }
            } else {
                return Result.createByResultEnum(ResultEnum.GET_WX_UNIONID_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.GET_WX_UNIONID_ERROR);
        }
    }*/


   /* *//**
     * 获取用户信息
     * @return
     *//*
    @PostMapping("/member/session")
    public Result decodeUserInfo() {

        Member sessioMember = (Member) session.getAttribute("member");
        if (sessioMember == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        Member voMember = new Member();
        voMember.setHeadimgurl(sessioMember.getHeadimgurl());
        voMember.setMemberNickname(sessioMember.getMemberNickname());
        return Result.createByResultEnum(ResultEnum.SUCCESS, voMember);
    }*/

}
